import copy
import time

import pygame
import sys
import random
import os
from game.snake.entity.block import Block
from game.snake.utils.block_action import BlockAction
from game.snake.utils.utils import Utils

pygame.init()

# 移动步长
step = 50
width_screen = 20
height_screen = 15
# 设置窗口大小和标题
screen = pygame.display.set_mode((step*width_screen, step*height_screen))
pygame.display.set_caption("射击消除小游戏")
# 背景图片
background_image_path = "img_sky.png"
# 方块图片
block_img_bee_path = "bee.png"
block_img_flower_path = "flower.png"

# 设置背景颜色为淡蓝色
bg_color = (155,196,226)
red = (255,0,0)
# 方块集合
block_list = []
# 排除数字结合
exclude_nums = [1,2]
# 移动速度
speed = 2.5
# 分数
score = 0

# 上一次 末尾位置
block_last = [Block(0,0,50,50,(255,255,255))]
# 运行状态
running = True
# 文件路径
main_dir = os.path.split(os.path.abspath(__file__))[0]

# 设置得分
score = 0
# 创建字体对象并设置字体和字号
font = pygame.font.Font(None, 36)
# 在屏幕右上角显示得分
score_color = (255, 255, 255)
score_text = font.render("Score: " + str(score), True, score_color)
screen.blit(score_text, (10, 10))

# 自动移动
def moveAuto(block_new):
    # moveAutoX(block_new)
    moveAutoY(block_new)

# x方向上自动移动
def moveAutoX(block_new):
    print("x位置：", block_new.x,",屏幕宽度", screen.get_width(),"", block_new.is_x_left,"y位置：", block_new.y,",屏幕高度", screen.get_height(),"", block_new.is_y_donw,"block_new_group:",
          len(block_new_group))
    if block_new.is_x_left:
        if block_new.x -speed >0:
            block_new.x-= speed
        else:
            block_new.is_x_left = False
    else:
        if block_new.x+speed <screen.get_width()-block_new.width:
            block_new.x+=speed
        else:
            block_new.is_x_left = True

# Y方向上移动
def moveAutoY(block_new):
    block_score = [ x for x in block_new_group if pygame.Rect(block_new.show()).colliderect(pygame.Rect(x.show())) and x !=block_new ]
    # 此处有个bug，碰撞后的方块位置不是step=50的整数，倒是后面转换2纬数组，可能两个方块的坐标一直
    if block_new.y -speed >=0 and len(block_score)==0:
        block_new.y-= speed
    else:
        # if len(block_score)>0:
        #     print("碰撞方块的位置：",block_score[0].show())
        #     block_new.y = block_score[0].y-speed
        block_new.is_y_donw = False


    return
    if block_new.is_y_donw:
        if block_new.y -speed >0:
            block_new.y-= speed
        else:
            block_new.is_y_donw = False
    else:
        if block_new.y + speed <screen.get_height()-block_new.height:
            block_new.y+=speed
        else:
            block_new.is_y_donw = True
# 消除整行
def process_array(arr):
    # 获取二维数组的行数和列数
    rows = len(arr)
    cols = len(arr[0]) if rows > 0 else 0
    not_none_all_row= []
    # 遍历第一行
    for row in range(rows):
        not_none_all = True
        for i in range(cols):
            # 检查元素是否为空
            if arr[row][i] is  None:
                not_none_all = False
                break
        if not_none_all:
            not_none_all_row.append(row)

    block_array = [[None for _ in range(cols)] for _ in range(rows)]
    row_array = 0
    # 删除第一行的所有元素
    for j in range(rows-1):
        if len([x for x in not_none_all_row if x == j])==0:
            block_array[row_array] = arr[j]
            row_array+= 1
    if len(not_none_all_row)>0:
        for row in range(len(block_array)):
            for col in range(len(block_array[row])):
                if block_array[row][col] is not None:
                    block_array[row][col].x = col*50
                    block_array[row][col].y = (row)*50

    return block_array

def list_2d():
    # 初始化二维数组
    max_x = screen.get_height() // 50 +1
    max_y = screen.get_width() // 50
    block_array = [[None for _ in range(max_y)] for _ in range(max_x)]
    for block in block_new_group:
        # 四舍五入
        x1 = round(block.y / 50)
        y1 = round(block.x / 50)
        block_array[x1][y1] = block
        print( block.y, block.x,x1,y1)
    return block_array
# 重新开始
def restart_game():
    global running,block_list,exclude_nums,block_new,score,block_new_group
    block_list = []
    exclude_nums = []
    block_new_group = []
    block_0 = Block(300,screen.get_height()-50,50,50,(255,255,255))

    # block_0.setText(pygame,"1")
    block_img_new = Utils.load_image(block_img_bee_path,block_0.size(),main_dir)
    block_0.setImage(block_img_new)
    block_list.append(block_0)

    block_new = newBlock()
    # block_new.setText(pygame,"2")
    # block_new_group.append(block_new)

    block_last = []
    score = 0
    return block_list

def newBlock():
    block_new_new = Block(0,0,50,50,(255,255,255))
    block_new_new.x = block_list[0].x
    block_new_new.y = block_list[0].y-step
    # block_new_new.x = abs(step * (random.randint(1, width_screen-1)))
    # block_new_new.y = abs(step * (random.randint(1, height_screen-1)))
    # block_new_new.x = abs(block_new_new.x)
    # block_new_new.y = abs(block_new_new.y)
    block_new_new.color = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
    #获取随机数字+字母
    random_num = Utils.getRandom(exclude_nums)
    # block_new_new.setText(pygame,str(chr(random_num)))
    block_img_new = Utils.load_image(block_img_flower_path,block_new_new.size(),main_dir)
    block_new_new.setImage(block_img_new)
    return block_new_new

def game_loop():
    global running,block_list,exclude_nums,block_new,time_start,main_dir,block_last,block_new_group,score
    # 开始时间
    time_start = time.time()
    # bg_music = Utils.load_sound("house_lo.wav",main_dir)
    # bg_music.play(-1)

    block_0 = Block(300,screen.get_height()-50,50,50,(255,255,255))
    # block_0.setText(pygame,"1")
    block_img = Utils.load_image(block_img_bee_path,block_0.size(),main_dir)
    block_0.setImage(block_img)
    block_list.append(block_0)
    if len(block_list)==1:
        block_last[0] = copy.copy(block_list[len(block_list)-1])
        block_last[0].x+= block_list[0].width
        block_new_group = []
        # block_new_group.append(newBlock())
    # 游戏循环
    while running:
        # 处理游戏事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                # 原地掉头
                # BlockAction.drawAll(block_list,-1,screen)
                block_new_group.append(newBlock())
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print("鼠标单机")
                if event.button == 1:
                    print("鼠标单机重新开始")
                    block_list = restart_game()
            # 更新小蜜蜂的位置
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT]:
                if block_list[0].x -step >=0:
                    BlockAction.moveAll(-step,0,block_list,"left",block_last)
            if keys[pygame.K_RIGHT]:
                if block_list[0].x +step < screen.get_width():
                    BlockAction.moveAll(step,0,block_list,"right",block_last)
            # if keys[pygame.K_UP]:
            #     if block_list[0].y -step >=0:
            #         BlockAction.moveAll(0,-step,block_list,"up",block_last)
            # if keys[pygame.K_DOWN]:
            #     if block_list[0].y + step < screen.get_height():
            #         BlockAction.moveAll(0,step,block_list,"down",block_last)


        # 碰撞
        block_score = [ x for x in block_new_group if pygame.Rect(block_list[0].show()).colliderect(pygame.Rect(x.show())) ]
        score+= len(block_score)
        if len(block_score)>0:
            file = "boom.wav"
            boom = Utils.load_sound(file,main_dir)
            boom.play()
        score_text = font.render("Score: " + str(score), True, score_color)

        # 没有碰撞
        block_new_group = [ x for x in block_new_group if pygame.Rect(block_list[0].show()).colliderect(pygame.Rect(x.show())) == False  ]
        # 绘制背景
        background_image = Utils.load_image(background_image_path,screen.get_size(),main_dir)
        background = pygame.Surface(screen.get_size())
        for x in range(0,screen.get_width(),background_image.get_width()):
            background.blit(background_image,(x,0))
            for y in range(0,screen.get_height(),background_image.get_height()):
                background.blit(background_image,(x,y))
        #设置背景颜色
        screen.fill(bg_color)
        # 设置背景图片
        screen.blit(background,(0,0))
        # 绘制方块
        BlockAction.drawAll(block_list,1,screen)
        # 方块图片
        # block_img = Utils.load_image(block_img_path,block_new.size(),main_dir)
        # block_new.setImage(block_img)
        # 自动移动
        for block_new_tem in block_new_group:
            moveAuto(block_new_tem)
        # 将block_new_group转换为二维数组
        block_new_group_2 = []
        if len(block_new_group)>0:
            block_new_group_array = list_2d()
            # 二维数组中，每一行满了的消除掉
            block_new_group_array = process_array(block_new_group_array)
            for row in range(len(block_new_group_array)):
                for col in range(len(block_new_group_array[row])):
                    if block_new_group_array[row][col] is not None:
                        block_new_group_2.append(block_new_group_array[row][col])
        print(len(block_new_group_2),len(block_new_group))
        block_new_group = block_new_group_2
        BlockAction.drawAll(block_new_group,1,screen)

        # for block_new_tem in block_new_group:

        # block_new.draw(screen,pygame)
        # BlockAction.drawAll(block_new_group,1,screen)
        screen.blit(score_text, (10, 10))
        # 更新屏幕显示
        pygame.display.update()
        time_now = time.time()
        if time_now-time_start> 1:
            time_start = time_now
            # 新增一个
            # block_new_group.append(newBlock())


    # 退出游戏
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    game_loop()
